const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const path = require('path');
const fs = require('fs');
const routes = require('./routes');
const { verifyToken } = require('./middleware/auth');
const app = express();
const { logger, morganStream } = require('./utils/logger');

// 配置CORS
app.use(cors({
  origin: ['http://localhost:5174', 'http://localhost:5175', 'http://localhost:3000'],
  credentials: true,
  exposedHeaders: ['X-Request-Id', 'Content-Disposition']
}));

// 关闭 ETag 并禁止 API 缓存，避免 304 导致前端拿不到数据
app.set('etag', false);
app.use((req, res, next) => {
  if (req.path && req.path.startsWith('/api/')) {
    res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
    res.set('Pragma', 'no-cache');
    res.set('Expires', '0');
    res.set('Surrogate-Control', 'no-store');
  }
  next();
});

// 请求调试中间件
app.use((req, res, next) => {
  console.log(`🌐 ${req.method} ${req.path}`);
  if (req.path.includes('/orders/') && req.path.includes('/status')) {
    console.log('🎯 订单状态更新请求检测到!');
  }
  next();
});

// 日志中间件
// app.use(morgan('dev'));
const env = process.env.NODE_ENV || 'development';
if (env === 'production' || env === 'staging') {
  app.use(morgan('combined', { stream: morganStream }));
} else {
  app.use(morgan('dev'));
}

// JSON解析中间件
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务
// 确保上传目录存在
const uploadsDir = path.join(__dirname, '../uploads');
const menuImagesDir = path.join(uploadsDir, 'menu-images');
if (!fs.existsSync(uploadsDir)) {
  logger.info(`创建上传根目录: ${uploadsDir}`);
  fs.mkdirSync(uploadsDir, { recursive: true });
}
if (!fs.existsSync(menuImagesDir)) {
  logger.info(`创建菜单图片目录: ${menuImagesDir}`);
  fs.mkdirSync(menuImagesDir, { recursive: true });
}

app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
app.use('/docs', express.static(path.join(__dirname, '../public')));
app.use('/images', express.static(path.join(__dirname, '../public/images')));

// 添加调试日志
app.use((req, res, next) => {
  if (req.url.includes('/uploads/menu-images/')) {
    logger.debug(`[静态文件请求] ${req.url}`);
    const urlWithoutQuery = req.url.split('?')[0];
    const filePath = path.join(__dirname, '..', urlWithoutQuery);
    logger.debug(`[静态文件路径] ${filePath}`);
    logger.debug(`[文件存在] ${fs.existsSync(filePath)}`);
  }
  next();
});

// 健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok' });
});

// V2导入专用健康检查
app.get('/healthz', (req, res) => {
  res.setHeader('X-Request-Id', req.headers['x-request-id'] || 'req_' + Date.now());
  res.status(200).json({ ok: true, timestamp: new Date().toISOString(), version: '2.0' });
});

// V2导入调试端点
app.get('/api/menu-import/v2/_debug', (req, res) => {
  res.setHeader('X-Request-Id', req.headers['x-request-id'] || 'req_' + Date.now());
  res.status(200).json({
    success: true,
    import_v2_enabled: process.env.IMPORT_V2 === 'true',
    environment: process.env.NODE_ENV || 'development',
    timestamp: new Date().toISOString(),
    available_routes: [
      'GET /v2/template/menu.xlsx',
      'POST /v2/validate',
      'POST /v2/commit',
      'GET /v2/jobs/:id'
    ]
  });
});

// 根路径处理
app.get('/', (req, res) => {
  res.json({
    success: true,
    message: 'CU MR BULL API 服务正在运行',
    version: '1.0.0',
    timestamp: new Date().toISOString(),
    documentation: '/api',
    healthCheck: '/health'
  });
});

// API根路径
app.get('/api', (req, res) => {
  res.json({
    success: true,
    message: 'CU MR BULL API 服务正在运行',
    version: '1.0.0',
    timestamp: new Date().toISOString(),
    documentation: '/docs/api-docs.html',
    endpoints: {
      auth: '/api/auth',
      users: '/api/users',
      menu: '/api/menu',
      orders: '/api/orders',
      dashboard: '/api/dashboard',
      system: '/api/system',
      socialMedia: '/api/social-media',
      invites: '/api/invites'
    }
  });
});

// 管理员API路由
app.use('/api/auth', routes.auth);
app.use('/api/dashboard', verifyToken, routes.dashboard);
app.use('/api/users', verifyToken, routes.users);
app.use('/api/menu', routes.menu); // 移除verifyToken中间件，让公共菜单路由可访问
app.use('/api/orders', routes.orders);
app.use('/api/coupons', verifyToken, routes.coupons);
app.use('/api/system', verifyToken, routes.system);
app.use('/api/reports', routes.reports); // 报表路由
app.use('/api/social-media', routes.socialMedia); // 社交媒体审核路由
app.use('/api/invites', routes.invites); // 邀请管理路由

// 管理员专用路由 - 需要更具体的路径在前面
// 菜单导入导出路由
app.use('/api/menu-import', routes.menuImport); // 菜单导入导出路由
app.use('/api/admin/menu-import', routes.menuImport); // 兼容旧路径
app.use('/api/admin', routes.couponImport); // 礼券导入导出路由（已包含认证中间件）

// 客户端API路由
app.use('/api/client/auth', routes.clientAuth);
app.use('/api/client/menu', routes.clientMenu);
app.use('/api/client/orders', routes.clientOrders);
app.use('/api/client/user', routes.clientUser);
app.use('/api/client/coupons', routes.clientCoupons);

// 管理员API - 通用管理路由（放在最后避免冲突）
app.use('/api/admin', routes.admin);

// 404处理器
app.use('/api/*', (req, res) => {
  logger.warn(`❌ 404处理器被触发: ${req.method} ${req.originalUrl} ${req.path}`);
  res.status(404).json({
    error: '接口不存在',
    message: `路径 ${req.originalUrl} 未找到`,
    code: 'ENDPOINT_NOT_FOUND'
  });
});

// 全局错误处理中间件
app.use((error, req, res, next) => {
  // 数据库错误
  if (error.code === 'ER_DUP_ENTRY') {
    return res.status(409).json({
      error: '数据已存在',
      message: '该记录已存在，请检查输入信息',
      code: 'DUPLICATE_ENTRY'
    });
  }
  
  // JWT错误
  if (error.name === 'JsonWebTokenError') {
    return res.status(401).json({
      error: '无效的访问令牌',
      message: '请重新登录',
      code: 'INVALID_TOKEN'
    });
  }
  
  if (error.name === 'TokenExpiredError') {
    return res.status(401).json({
      error: '访问令牌已过期',
      message: '请重新登录',
      code: 'TOKEN_EXPIRED'
    });
  }
  
  // 验证错误
  if (error.name === 'ValidationError') {
    return res.status(400).json({
      error: '数据验证失败',
      message: error.message,
      code: 'VALIDATION_ERROR'
    });
  }
  
  // 默认服务器错误
  res.status(error.status || 500).json({
    error: '服务器内部错误',
    message: process.env.NODE_ENV === 'development' ? error.message : '服务暂时不可用，请稍后重试',
    code: 'INTERNAL_SERVER_ERROR'
  });
});

// 启动服务器
// 导出app实例和PORT，让start-server.js负责启动

module.exports = app;